<template>
  <div class="container p-6">
    <!-- 面包屑导航 -->
    <div class="breadcrumb mb-4">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/teacher/exam' }"
          >考试管理</el-breadcrumb-item
        >
        <el-breadcrumb-item>添加考试</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 组卷信息 -->
    <div class="card mb-6">
      <div class="card-header">
        <h2 class="text-lg font-bold">组卷信息</h2>
        <div class="text-right text-red-500 font-bold">
          试卷总分: {{ totalScore }} 分
        </div>
      </div>
      <div class="card-body p-4">
        <div class="grid grid-cols-9 gap-2 items-center">
          <div class="col-span-1 text-center">题库</div>
          <div class="col-span-1 text-center">单选数量</div>
          <div class="col-span-1 text-center">单选分数</div>
          <div class="col-span-1 text-center">多选数量</div>
          <div class="col-span-1 text-center">多选分数</div>
          <div class="col-span-1 text-center">判断题数量</div>
          <div class="col-span-1 text-center">判断题分数</div>
          <div class="col-span-1 text-center">简答题数量</div>
          <div class="col-span-1 text-center">简答题分数</div>
        </div>

        <div class="grid grid-cols-9 gap-2 mt-2">
          <div class="col-span-1">
            <el-select
              v-model="form.repoId"
              placeholder="选择题库"
              class="w-full"
              size="large"
              @change="handleRepoChange"
            >
              <el-option
                v-for="item in repoList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="col-span-1 relative">
            <el-input
              v-model="form.radioCount"
              :min="0"
              :max="selectedRepo ? selectedRepo.radioNum : 0"
              class="w-full"
              size="large"
              style="width: 60px"
            />
            <div
              class="absolute right-6 top-1/2 transform -translate-y-1/2 text-base text-gray-500 whitespace-nowrap"
            >
              / {{ selectedRepo?.radioNum || 0 }}
            </div>
          </div>
          <div class="col-span-1">
            <el-input
              v-model="form.radioScore"
              :min="0"
              class="w-full"
              size="large"
            />
          </div>
          <div class="col-span-1 relative">
            <el-input
              v-model="form.multiCount"
              :min="0"
              :max="selectedRepo ? selectedRepo.multiNum : 0"
              class="w-full"
              size="large"
              style="width: 60px"
            />
            <div
              class="absolute right-6 top-1/2 transform -translate-y-1/2 text-base text-gray-500 whitespace-nowrap"
            >
              / {{ selectedRepo?.multiNum || 0 }}
            </div>
          </div>
          <div class="col-span-1">
            <el-input
              v-model="form.multiScore"
              :min="0"
              class="w-full"
              size="large"
            />
          </div>
          <div class="col-span-1 relative">
            <el-input
              v-model="form.judgeCount"
              :min="0"
              :max="selectedRepo ? selectedRepo.judgeNum : 0"
              class="w-full"
              size="large"
              style="width: 60px"
            />
            <div
              class="absolute right-6 top-1/2 transform -translate-y-1/2 text-base text-gray-500 whitespace-nowrap"
            >
              / {{ selectedRepo?.judgeNum || 0 }}
            </div>
          </div>
          <div class="col-span-1">
            <el-input
              v-model="form.judgeScore"
              :min="0"
              class="w-full"
              size="large"
            />
          </div>
          <div class="col-span-1 relative">
            <el-input
              v-model="form.saqCount"
              :min="0"
              :max="selectedRepo ? selectedRepo.saqNum : 0"
              style="width: 60px"
              class="w-full"
              size="large"
            />
            <div
              class="absolute right-6 top-1/2 transform -translate-y-1/2 text-base text-gray-500 whitespace-nowrap"
            >
              / {{ selectedRepo?.saqNum || 0 }}
            </div>
          </div>
          <div class="col-span-1">
            <el-input
              v-model="form.saqScore"
              :min="0"
              class="w-full"
              size="large"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 考试配置 -->
    <div class="card">
      <div class="card-header">
        <h2 class="text-lg font-bold">考试配置</h2>
      </div>
      <div class="card-body">
        <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          class="max-w-4xl mx-auto"
          size="large"
        >
          <div class="grid grid-cols-2 gap-6">
            <el-form-item label="考试名称" prop="title" required>
              <el-input
                v-model="form.title"
                placeholder="请输入考试名称"
                size="large"
              />
            </el-form-item>

            <el-form-item label="总分数" prop="grossScore">
              <el-input-number
                v-model="totalScore"
                :min="0"
                disabled
                class="w-full"
                size="large"
              />
            </el-form-item>

            <el-form-item label="及格分" prop="passedScore" required>
              <el-input-number
                v-model="form.passedScore"
                :min="0"
                :max="totalScore"
                class="w-full"
                size="large"
              />
            </el-form-item>

            <el-form-item label="最多切屏次数" prop="maxCount">
              <el-input-number
                v-model="form.maxCount"
                :min="0"
                class="w-full"
                size="large"
              />
            </el-form-item>

            <el-form-item label="证书" prop="certificate">
              <el-select
                v-model="form.certificateId"
                placeholder="选择或搜索证书"
                class="w-full"
                size="large"
              >
                <el-option label="不授予证书" value="0" />
                <el-option
                  v-for="item in certificateList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="考试时长(分钟)" prop="examDuration" required>
              <el-input-number
                v-model="form.examDuration"
                :min="1"
                class="w-full"
                size="large"
              />
            </el-form-item>
          </div>

          <el-form-item label="考试时间范围" prop="timeRange" required>
            <el-config-provider :locale="zhCn">
              <el-date-picker
                v-model="form.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="w-full"
                :shortcuts="[]"
                :clearable="false"
                size="large"
              />
            </el-config-provider>
          </el-form-item>

          <el-form-item label="考试班级" prop="gradeIds" required>
            <el-select
              v-model="form.gradeIds"
              placeholder="选择或搜索班级"
              multiple
              class="w-full"
              size="large"
            >
              <el-option
                v-for="item in gradeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <div class="flex justify-center gap-4 mt-6">
              <el-button type="primary" size="large" @click="submitForm"
                >保存</el-button
              >
              <el-button size="large" @click="goBack">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElConfigProvider } from 'element-plus'
import { useRouter } from 'vue-router'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { getRepolist } from '@/api/teacher/question'
import { getGradelist } from '@/api/teacher/classmanage'
import { getCertificateList } from '@/api/teacher/certificate'
import { addExam } from '@/api/teacher/exam'

const router = useRouter()
const formRef = ref(null)

// 题库列表
const repoList = ref([])
// 班级列表
const gradeList = ref([])
// 证书列表
const certificateList = ref([])

// 表单数据
const form = reactive({
  title: '',
  examDuration: 60,
  maxCount: 0,
  passedScore: 0,
  startTime: '',
  endTime: '',
  gradeIds: [],
  repoId: '',
  certificateId: 0,
  radioCount: 0,
  radioScore: 0,
  multiCount: 0,
  multiScore: 0,
  judgeCount: 0,
  judgeScore: 0,
  saqCount: 0,
  saqScore: 0,
  timeRange: [],
})

// 存储选中的题库信息
const selectedRepo = ref(null)

// 计算总分
const totalScore = computed(() => {
  return (
    form.radioCount * form.radioScore +
    form.multiCount * form.multiScore +
    form.judgeCount * form.judgeScore +
    form.saqCount * form.saqScore
  )
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入考试名称', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
  ],
  passedScore: [
    { required: true, message: '请输入及格分', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value > totalScore.value) {
          callback(new Error('及格分不能大于总分'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  examDuration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' },
  ],
  timeRange: [
    { required: true, message: '请选择考试时间范围', trigger: 'change' },
  ],
  gradeIds: [{ required: true, message: '请选择考试班级', trigger: 'change' }],
}

// 初始化页面
onMounted(async () => {
  try {
    // 获取题库列表
    const { code: repoCode, data: repoData } = await getRepolist()
    if (repoCode !== 0 && repoData) {
      // 题库数据结构: {id, title, radioNum, multiNum, judgeNum, saqNum}
      repoList.value = repoData.map((item) => ({
        label: item.title, // 显示题库标题
        value: item.id.toString(), // 提交题库ID
        radioNum: item.radioNum, // 保存题目数量信息用于后续可能的逻辑
        multiNum: item.multiNum,
        judgeNum: item.judgeNum,
        saqNum: item.saqNum,
      }))
    }

    // 获取班级列表
    const { data: gradeData } = await getGradelist()
    if (gradeData && gradeData.records) {
      gradeList.value = gradeData.records.map((item) => ({
        label: item.gradeName,
        value: item.id.toString(),
      }))
    }

    // 获取证书列表
    // const { code: certCode, data: certData } = await getCertificateList()
    // if (certCode !== 0 && certData) {
    //   certificateList.value = certData.map((item) => ({
    //     label: item.name,
    //     value: item.id.toString(),
    //   }))
    // }
  } catch (error) {
    console.error('获取基础数据失败:', error)
    ElMessage.error('获取数据失败，请刷新重试')
  }
})

// 处理题库选择变化
const handleRepoChange = (repoId) => {
  // 查找选择的题库信息
  selectedRepo.value = repoList.value.find((repo) => repo.value === repoId)

  if (selectedRepo.value) {
    // 设置题目数量为题库最大数量
    form.radioCount = selectedRepo.value.radioNum || 0
    form.multiCount = selectedRepo.value.multiNum || 0
    form.judgeCount = selectedRepo.value.judgeNum || 0
    form.saqCount = selectedRepo.value.saqNum || 0

    // 默认每题1分
    form.radioScore = form.radioCount > 0 ? 1 : 0
    form.multiScore = form.multiCount > 0 ? 1 : 0
    form.judgeScore = form.judgeCount > 0 ? 1 : 0
    form.saqScore = form.saqCount > 0 ? 1 : 0
  } else {
    form.radioCount = 0
    form.multiCount = 0
    form.judgeCount = 0
    form.saqCount = 0
    form.radioScore = 0
    form.multiScore = 0
    form.judgeScore = 0
    form.saqScore = 0
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 处理时间范围
        const [startTime, endTime] = form.timeRange || []

        // 构建提交数据
        const submitData = {
          title: form.title,
          examDuration: form.examDuration,
          maxCount: form.maxCount,
          passedScore: form.passedScore,
          startTime: startTime,
          endTime: endTime,
          gradeIds: Array.isArray(form.gradeIds)
            ? form.gradeIds.join(',')
            : form.gradeIds,
          repoId: form.repoId,
          certificateId: form.certificateId || 0,
          radioCount: form.radioCount,
          radioScore: form.radioScore,
          multiCount: form.multiCount,
          multiScore: form.multiScore,
          judgeCount: form.judgeCount,
          judgeScore: form.judgeScore,
          saqCount: form.saqCount,
          saqScore: form.saqScore,
        }

        // 调用添加API
        const { code, msg } = await addExam(submitData)

        if (code === 0) {
          ElMessage.error('添加失败：' + (msg || '未知错误'))
          return
        }

        ElMessage.success('添加成功')
        router.push('/teacher/exam')
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请稍后重试')
      }
    } else {
      console.log('表单验证失败:', fields)
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push('/teacher/exam')
}
</script>

<style lang="less" scoped>
.container {
  background-color: white;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

.breadcrumb {
  font-size: 14px;
  color: #606266;
}

.card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
  overflow: hidden;

  .card-header {
    padding: 16px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f8f9fa;
  }

  .card-body {
    padding: 20px;
  }
}

:deep(.el-input-number) {
  width: 100%;

  .el-input__wrapper {
    padding-right: 0;
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item.is-required > .el-form-item__label::before) {
  color: #f56c6c;
}

:deep(.el-date-editor) {
  --el-date-editor-width: 100%;
}

:deep(.el-picker-panel) {
  .el-date-table th {
    color: #606266;
    font-weight: 500;
  }

  .el-date-picker__header-label {
    font-weight: 500;
  }

  .el-date-range-picker__time-header {
    border-bottom: 1px solid #ebeef5;
  }
}
</style>
